const models = require("../../model");
const { APIError } = require("../../rest");
const { Op } = require("sequelize");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const secret = "xion_secret";

const Users = models.User;

// 定义用户模型
class UserModel {
  // 注册用户
  static async register(params) {
    let { username, email, password } = params;
    const hasUsername = await Users.findOne({
      where: {
        username,
      },
    });
    const hasEmail = await Users.findOne({
      where: {
        email,
      },
    });
    // 判断用户是否已存在
    if (hasUsername) {
      throw new APIError("User: existing", "用户名已被注册");
    }
    if (hasEmail) {
      throw new APIError("User: existing", "邮箱已被注册");
    }
    Users.create({
      username,
      email,
      password,
    });
  }

  // 登录
  static async login(params) {
    let { email, password } = params;

    let hasEmail = await Users.findOne({
      where: {
        email,
      },
    });
    // 判断用户是否已存在
    if (!hasEmail) {
      throw new APIError("Email: Not Found", "邮箱不存在");
    }

    // 验证密码是否正确
    const correct = bcrypt.compareSync(password, hasEmail.password);

    if (!correct) {
      throw new APIError("Password: error", "密码不正确");
    }
    const { id, username, email: mail } = hasEmail;
    const payload = Object.assign({}, { id, username, email: mail });
    const expiresIn = 60 * 60 * 24; // 单位s
    const token = jwt.sign(payload, secret, { expiresIn });

    // 更新用户token
    hasEmail.token = token;
    hasEmail.save();

    return token;
  }

  // 查询列表
  static async queryList(query) {
    let { username, email, page, pageSize } = query;
    let filter = {};
    if (username) {
      Object.assign(filter, { username: { [Op.like]: `%${username}%` } });
    }
    if (email) {
      Object.assign(filter, { email: { [Op.like]: `%${email}%` } });
    }

    page = +page;
    pageSize = +pageSize;
    const users = await Users.findAndCountAll({
      limit: pageSize, //每页10条
      offset: (page - 1) * pageSize,
      where: filter,
      order: [["createdTime", "DESC"]],
    });

    return users;
  }

  // 删除用户
  static async delete(id) {
    const User = await Users.findOne({
      where: {
        id,
      },
    });

    if (!User) {
      throw new APIError("User: not_found", "用户不存在！");
    }
    // 软删除用户
    User.destroy();
  }

  // 修改密码
  static async update(params) {
    let { id, password } = params;
    // 查询当前商品
    let User = await Users.findByPk(id);
    if (!User) {
      throw new APIError("User: not_found", "用户不存在！");
    }
    User.password = password;
    User.save();
  }

  // 查询用户信息
  static async getUserInfo(token) {
    console.log("token----------------", token);
    const User = await Users.findOne({
      where: { token },
      attributes: ["username", "email"],
    });
    console.log("User-----------------------", User);
    if (!User) {
      throw new APIError("authentication: error", "未授权，请重新登录");
    }

    return User;
  }
}

module.exports = {
  Users: UserModel,
};
